package com.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.bean.PageBean;
import com.hc.constant.SkuConst;
import com.hc.domain.Comment;
import com.hc.domain.CommentTag;
import com.hc.domain.Order;
import com.hc.domain.OrderItem;
import com.hc.domain.Sku;
import com.hc.domain.Tag;
import com.hc.domain.User;
import com.hc.mapper.CommentMapper;
import com.hc.query.CommentItem;
import com.hc.query.CommentVO;
import com.hc.res.CommentWithTag;
import com.hc.res.UserComment;
import com.hc.service.CommentService;
import com.hc.service.CommentTagService;
import com.hc.service.OrderItemService;
import com.hc.service.OrderService;
import com.hc.service.SkuService;
import com.hc.service.TagService;
import com.hc.service.UserService;
import com.hc.trans.CommentTrans;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hecai
 * @date 2021/12/17 17:36
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private SkuService skuService;
    @Resource
    private OrderService orderService;
    @Resource
    private UserService userService;

    @Override
    public PageBean<UserComment> getUserCommentListBySkuId(Integer skuId, Integer pageNum, Integer pageSize) {
        //获取skuId所属的spu下的所有sku的集合
        Sku sku = skuService.getOne(new QueryWrapper<Sku>().select("spu_id").eq("status", SkuConst.Status.ok).eq("id", skuId));
        List<Sku> skuList = skuService.list(new QueryWrapper<Sku>().select("id").eq("status", SkuConst.Status.ok).eq("spu_id", sku.getSpuId()));
        //获取sku的集合中的sku id集合
        List<Integer> skuIdList = skuList.stream().map(item -> item.getId()).collect(Collectors.toList());

        //查找所有的评论信息
        Page<Comment> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<Comment>()
                .eq("status", SkuConst.Status.ok)
                .orderByDesc("create_time")
                .in("sku_id", skuIdList);
        baseMapper.selectPage(page, queryWrapper);

        //将Comment中的userId的值映射到id字段上，便于下面MapStruct转换使用
        for (Comment comment : page.getRecords()) {
            comment.setId(comment.getUserId());
        }

        PageBean<Comment> commentPageBean = PageBean.init(page);
        PageBean<UserComment> userCommentPageBean = CommentTrans.MAPPER.commentPageBean2UserCommentPageBean(commentPageBean);
        for (UserComment userComment : userCommentPageBean.getRecords()) {
            User user = userService.getById(userComment.getId());
            userComment.setAvatar(user.getAvatar());
            userComment.setName(user.getNickname());
        }
        return userCommentPageBean;
    }

    @Resource
    private CommentTagService commentTagService;
    @Resource
    private TagService tagService;

    @Override
    public PageBean<CommentWithTag> getCommentWithTag(Integer pageNum, Integer pageSize, Long userId) {
        //分页查询出userId指定页的Comment
        Page<Comment> page = new Page<>(pageNum, pageSize);
        baseMapper.selectPage(page, new QueryWrapper<Comment>().eq("user_id", userId));

        //将这一页的Comment信息转换为CommentWithTag
        List<CommentWithTag> commentWithTagList = new ArrayList<>();
        for (Comment comment : page.getRecords()) {
            List<CommentTag> commentTagList = commentTagService.list(new QueryWrapper<CommentTag>().eq("comment_id", comment.getId()));
            List<String> titleList = new ArrayList<>();
            for (CommentTag commentTag : commentTagList) {
                Tag tag = tagService.getById(commentTag.getTagId());
                titleList.add(tag.getTitle());
            }
            CommentWithTag commentWithTag = CommentTrans.MAPPER.commentAndTags2CommentWithTag(comment, titleList);
            commentWithTagList.add(commentWithTag);
        }

        PageBean<CommentWithTag> pageBean = new PageBean<>();
        pageBean.setPageSize((int) page.getSize());
        pageBean.setCurrent(page.getCurrent());
        pageBean.setPages(page.getPages());
        pageBean.setRecords(commentWithTagList);
        return pageBean;
    }

    @Resource
    private OrderItemService orderItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveComment(CommentVO commentVO) {
        Order order = Order.builder()
                .id(commentVO.getOrderId())
                .desIdentical(commentVO.getDesIdentical())
                .logisticServe(commentVO.getLogisticServe())
                .serveAttitude(commentVO.getServeAttitude())
                .build();
        //更新订单
        orderService.updateById(order);

        List<CommentItem> commentItemList = commentVO.getCommentItemList();
        for (CommentItem commentItem : commentItemList) {
            //添加评论
            Comment comment = CommentTrans.MAPPER.commentItem2Comment(commentItem);
            baseMapper.insert(comment);

            //添加评论对应的标签
            List<Integer> tagList = commentItem.getTagList();
            List<CommentTag> commentTagList = new ArrayList<>();
            for (Integer tagId : tagList) {
                commentTagList.add(CommentTag.builder()
                        .commentId(comment.getId())
                        .tagId(tagId)
                        .build());
            }
            commentTagService.saveBatch(commentTagList);

            //更新评论的条数
            //修改OrderItem中的评论数量
            OrderItem orderItem = OrderItem.builder().comments(SkuConst.Comment.FIRST).build();
            orderItemService.update(orderItem, new QueryWrapper<OrderItem>()
                    .eq("order_id", commentItem.getOrderId())
                    .eq("sku_id", commentItem.getSkuId()));
        }
    }

    @Override
    public UserComment getUserComment(Long commentId) {
        Comment comment = baseMapper.selectById(commentId);
        User user = userService.getOne(new QueryWrapper<User>().eq("id", comment.getUserId()));
        UserComment userComment = comment2UserComment(user, comment);

        return userComment;
    }

    private UserComment comment2UserComment(User user, Comment comment) {
        UserComment userComment = new UserComment();
        if (user != null) {
            userComment.setId(user.getId());
            userComment.setAvatar(user.getAvatar());
            userComment.setName(user.getNickname());
        }

        if (comment != null) {
            userComment.setPics(comment.getPics());
            userComment.setContent(comment.getContent());
            userComment.setStars(comment.getStars());
            userComment.setComments(comment.getComments());
            userComment.setAgrees(comment.getAgrees());
        }

        return userComment;
    }
}
